package cn.itsource.basic.other.aop;

import cn.itsource.basic.other.annotation.Repeat;
import cn.itsource.basic.other.exception.BusinessException;
import cn.itsource.basic.util.RedisService;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class RepeatAop {
    @Autowired
    private RedisService redisService;


    @Pointcut("@annotation(repeat)")
    public void cut(Repeat repeat) {

    }

    @Before("cut(repeat)")
    public void repeat(Repeat repeat) {
        //1.获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String ipAddress = request.getRemoteAddr() + request.getRequestURI();

        String key = redisService.getKeyStringValue(ipAddress);
        if (key != null) {
            throw new BusinessException("请不要重复请求!");
        }

        redisService.setStringKeyAndValue(ipAddress, "123456", repeat.value());
    }
}
